package com.example.demo.plugin;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.domain.Bot;
import com.example.demo.domain.BotPlugin;
import com.example.demo.event.GroupMessageEvent;
import org.springframework.stereotype.Component;

import static com.example.demo.config.MessageConfig.MESSAGE_BLANK;
import static com.example.demo.config.MessageConfig.MESSAGE_IN;

/**
 * 疫情查询
 *
 * @author bystart
 * @version 1.0
 * @date 2021/11/4 4:19 下午
 */
@Component
public class NCov extends BotPlugin {
    final String N_COV_URL = "https://lab.isaaclin.cn/nCoV/api/area?latest=1&province=%s";
    @Override
    public int onGroupMessage(Bot bot, GroupMessageEvent event) {
        String key = "疫情";
        String message = event.getMessage();
        if (message.endsWith(key)){
            String addr = message.replace(key, "").replaceAll("\\s*", "");
            JSONObject object = JSONUtil.parseObj(HttpUtil.get("https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5"));
            JSONObject data = object.getJSONObject("data");
            JSONObject areaTree = (JSONObject) data.getJSONArray("areaTree").get(0);
            JSONArray children = areaTree.getJSONArray("children");
            for (Object o : children) {
                JSONObject o1 = (JSONObject) o;
                JSONArray children1 = o1.getJSONArray("children");
                for (Object o2 : children1) {
                    JSONObject o3 = (JSONObject) o2;
                    if (o3.getStr("name").indexOf(addr)!= -1){
                        JSONObject total = o3.getJSONObject("total");
                        JSONObject today = o3.getJSONObject("today");
                        StringBuffer sb = new StringBuffer();
                        sb.append("地区：" + o3.getStr("name") + "\n");
                        sb.append("今日新增：" + today.getStr("confirm")+"例\n");
                        sb.append("现有确诊：" + total.getStr("nowConfirm")+"例");
                        bot.sendGroupMessage(event.getGroupId(),sb.toString(),null,null,false);
                        return MESSAGE_BLANK;
                    }
                }
            }
        }
        return MESSAGE_IN;
    }
}
